package cn.framelife.rainbow.ui.provider;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import cn.framelife.rainbow.constant.Constant;
import cn.framelife.rainbow.util.xml.ConnectionXMLUtil;

/**
 * 数据库连接页面内容提供者
 * 
 * @author 潘广伟 p_3er@qq.com  
 * @date 2014-3-26 下午4:01:03
 */
public class ConnectionPageProvider {
	/**
	 * 
	 * 从配置文件中获取数据库模板及驱动名称
	 * 
	 * @Title: getDatabaseTemplates 
	 * @param   
	 * @return void     
	 * @throws Exception 
	 */
	public Properties loadDatabaseTemplates() throws Exception {	
		Properties databaseTemplates = new Properties();
		InputStream in = getClass().getResourceAsStream(Constant.DBTEMPFILE);
		databaseTemplates.load(in);

        
        return databaseTemplates;
	}
	
	public String[] getDriverTemplateItems(Properties databaseTemplates ) throws Exception{
		Enumeration en = databaseTemplates.propertyNames();
		String[] driverTemplateItems = new String[databaseTemplates.size()];
		int itemNum = 0;
        while (en.hasMoreElements()) {
        	driverTemplateItems[itemNum] = (String) en.nextElement();
        	itemNum++;
        }
        
        return driverTemplateItems;
	}
	
	public Properties loadDriverNames() throws Exception {	
		 Properties driverNames = new Properties();
		 InputStream driverNamesIn = getClass().getResourceAsStream(Constant.DRIVERNAMEFILE);
		 driverNames.load(driverNamesIn);
		 
		 return driverNames;
	}
	
	/**
	 * 获取已有连接
	 *
	 * @return
	 * @throws Exception
	 */
	public String[] getConnectionNames() throws Exception{
		Document doc = ConnectionXMLUtil.createConnectionXML();
		NodeList list = doc.getElementsByTagName("connection");
		String[] items = new String[list.getLength()] ;
		for(int i = 0; i< list.getLength() ; i ++){
            Element node = (Element)list.item(i);
            items[i] = ConnectionXMLUtil.getValue(node, "name");
		}
		
		return items;
	}
}
